import { Injectable } from '@nestjs/common';
import { CreateDictTypeDto } from './dto/create-dict-type.dto';
import { UpdateDictTypeDto } from './dto/update-dict-type.dto';
import { QueryDictTypeDto } from './dto/query-dict-type.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { DictType } from './entities/dict-type.entity';
import { Repository } from 'typeorm';
import { Request,Response } from 'express';
import { User } from '../user/entities/user.entity';
import { DeleteDictTypeDto } from './dto/delete-dict-type.dto';
import { StatusChangeDto } from 'src/common/baseDto/status-change.dto';
import { Workbook } from 'exceljs';

@Injectable()
export class DictTypeService {
  constructor(
    @InjectRepository(DictType)
    private readonly dictTypeRepository: Repository<DictType>,
  ) {}

  /**
   * 创建字典类型
   * @param createDictTypeDto
   * @param req
   * @returns
   */
  create(createDictTypeDto: CreateDictTypeDto, req: Request) {
    let user = req.user as User;
    createDictTypeDto.create_by = user.username;
    return this.dictTypeRepository.save(createDictTypeDto);
  }

  /**
   * 获取字典类型列表
   * @param query
   * @returns
   */
  async findAll(query: QueryDictTypeDto) {
    let queryBuilder = this.dictTypeRepository.createQueryBuilder('dictType');
    if (query.dict_name) {
      queryBuilder = queryBuilder.andWhere(
        'dictType.dict_name like :dict_name',
        { dict_name: `%${query.dict_name}%` },
      );
    }
    if (query.dict_code) {
      queryBuilder = queryBuilder.andWhere(
        'dictType.dict_code like :dict_code',
        { dict_code: `%${query.dict_code}%` },
      );
    }
    if (query.status) {
      queryBuilder = queryBuilder.andWhere('dictType.status = :status', {
        status: query.status,
      });
    }
    if (query.begin_time && query.end_time) {
      queryBuilder = queryBuilder.andWhere(
        'dictType.create_time between :begin_time and :end_time',
        { begin_time: query.begin_time, end_time: query.end_time },
      );
    }

    // 处理分页
    if (!query.pageNum || query.pageNum < 1) {
      query.pageNum = 1;
    }
    if (!query.pageSize || query.pageSize < 1) {
      query.pageSize = 10;
    }
    queryBuilder = queryBuilder
      .groupBy('dictType.dict_id')
      .skip((query.pageNum - 1) * query.pageSize)
      .take(query.pageSize);

    let total = await queryBuilder.getCount();
    let list = await queryBuilder.getMany();
    return {
      pageNum: query.pageNum,
      pageSize: query.pageSize,
      total: total,
      list: list,
    };
  }

  /**
   * 获取所有字典类型
   * @returns 
   */
  getDictType() {
    return this.dictTypeRepository.find();
  }

  /**
   * 获取字典类型详情
   * @param id
   * @returns
   */
  findOne(id: number) {
    return this.dictTypeRepository.findOne({ where: { dict_id: id } });
  }

  /**
   * 更新字典类型
   * @param id
   * @param updateDictTypeDto
   * @param req
   * @returns
   */
  update(id: number, updateDictTypeDto: UpdateDictTypeDto, req: Request) {
    let user = req.user as User;
    updateDictTypeDto.dictType.update_by = user.username;
    return this.dictTypeRepository.update(id,updateDictTypeDto.dictType);
  }
  
  /**
   * 更新字典类型状态
   * @param statusChangeDto
   * @param req
   */
  statusChange(statusChangeDto: StatusChangeDto,req: Request) {
    let user = req.user as User;
    return this.dictTypeRepository.update(statusChangeDto.id, {
      status: statusChangeDto.status,
      update_by: user.username
    });
  }

  /**
   * 删除字典类型
   * @param deleteDictTypeDto
   * @returns
   */
  remove(deleteDictTypeDto: DeleteDictTypeDto) {
    return this.dictTypeRepository.delete(deleteDictTypeDto.dictTypeIds);
  }

  
  /**
   * 导出为表格
   * @param res
   */
  async exportToExcel(res: Response) {
    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet('字典类型');

    worksheet.columns = [
      { header: '字典类型ID', key: 'dict_id', width: 10 },
      { header: '字典类型名称', key: 'dict_name', width: 10 },
      { header: '字典类型', key: 'dict_type', width: 10 },
      { header: '状态（0：正常，1：禁用）', key: 'status', width: 10 },
      { header: '创建者', key: 'create_by', width: 10 },
      { header: '创建时间', key: 'create_time', width: 10 },
      { header: '更新者', key: 'update_by', width: 10 },
      { header: '更新时间', key: 'update_time', width: 10 },
      { header: '备注', key: 'remark', width: 10 },
    ];

    const data = await this.dictTypeRepository.find();
    worksheet.addRows(data);
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    let filename = encodeURIComponent('字典类型.xlsx'); // 这里中文需要转码
    res.setHeader(
      'Content-Disposition',
      'attachment; filename=' + filename + '',
    );
    res.setHeader('Cache-Control', 'max-age=0');
    const file = await workbook.xlsx.writeBuffer();
    res.end(file);
  }
}
